package com.shengwei.truck.driver.utils;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.util.Log;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.core.content.FileProvider;

import com.google.gson.Gson;
import com.lzy.okhttputils.OkHttpUtils;
import com.lzy.okhttputils.callback.FileCallback;
import com.lzy.okhttputils.request.GetRequest;
import com.shengwei.truck.driver.R;
import com.shengwei.truck.driver.bean.AppInfo;
import com.shengwei.truck.driver.bean.MyConstant;
import com.shengwei.truck.driver.bean.User;
import com.shengwei.truck.driver.utils.okhttputils.StringCallback;
import com.shengwei.truck.driver.view.ui.ActivityCollectorUtil;
import com.shengwei.truck.driver.view.ui.app.MyApplication;

import org.json.JSONObject;
import java.io.File;
import java.lang.ref.WeakReference;
import okhttp3.Call;
import okhttp3.Request;
import okhttp3.Response;

/**
 * APP升级功能
 * xw.gao on 2018/5/8
 */

public class UpdateApp {

    static  String TAG = "UpdateApp";
    Context mContext;
    int mLocalAppVersionCode = 0;

    //用于下载进度
    private ProgressDialog mDownLoadProgressDlg;
    int downloadCount = 0; //用于控制通知栏进度条的更新速度
    public static final int CHECK_ONLY = 0;
    public static final int CHECK_AND_DOWNLOAD = 1;


    public UpdateApp(Context context) {

        mContext = context;
    }
    public interface GetAppInfoListener
    {
        abstract void onSuccess(AppInfo appInfo, int checkType);
        abstract void onFailed(String errMsg);
    }
    public interface DownLoadListener
    {
        abstract void onSuccess();
        abstract void onFailed();
        abstract void onProgress(int progress);
    }
    /**
     * 检查新版本
     * @param checkType  0只检查新版本, 1 检查新版本并升级
     */
    public  void checkUpdate(final int checkType, GetAppInfoListener getAppListener) {
        mLocalAppVersionCode  = getVersionCode(mContext);

        if(mLocalAppVersionCode == -1) {
            WeakReference<Context> contextWeakReference = new WeakReference<>(mContext);
            String tip = "本地APP版本号获取失败";
            MyToast.showToastCenter(contextWeakReference,tip, Toast.LENGTH_SHORT,true);
            return;
        }
        getServerAPPInfo(mContext,getAppListener,checkType,mLocalAppVersionCode);
        return;
    }

    /**
     * 安装APK
     * @param apkFile
     */
    public static void install(File apkFile,Context context) {
        //退出所有页面，清除token
        ActivityCollectorUtil.finishAllActivity();
        User user = User.getInstance(context.getApplicationContext());
        user.setToken("");
        user.setHeadImvUrl("");

        //开始安装
        Intent intent = new Intent();
        //安装完成后，启动app
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setAction(Intent.ACTION_VIEW);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            Uri uri = FileProvider.getUriForFile(context, context.getPackageName() + "", apkFile);//第二个参数要和Mainfest中<provider>内的android:authorities 保持一致
            intent.setDataAndType(uri, "application/vnd.android.package-archive");
        } else {
            intent.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");
        }
        context.startActivity(intent);
        return;
    }


    public void downLoad(final  String url,String updateContent,final DownLoadListener downLoadListener)
    {
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
        builder.setTitle("提示");
        builder.setMessage(R.string.find_newer_version);
        builder.setPositiveButton("升级", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                dialogInterface.dismiss();

                downLoadApk(url,downLoadListener);
            }
        });

        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {

                dialogInterface.dismiss();
            }
        });
        AlertDialog dlg = builder.create();
        dlg.setCancelable(false);
        dlg.setCanceledOnTouchOutside(false);
        dlg.show();

        int colorPrimary = mContext.getResources().getColor(R.color.colorPrimary);
        int colorDescribe = mContext.getResources().getColor(R.color.describe_color);
        dlg.getButton(AlertDialog.BUTTON_POSITIVE).setTextColor(colorPrimary);
        dlg.getButton(DialogInterface.BUTTON_NEGATIVE).setTextColor(colorDescribe);
    }

    /**
     * 下载最新的APK安装包
     */
    public void downLoadApk(String url,final DownLoadListener downLoadListener) {

        if(MyApplication.UPDATE_STATE == 1)
        {
            WeakReference<Context> contextWeakReference = new WeakReference<>(mContext);
            String tip = mContext.getResources().getString(R.string.has_updating);
            MyToast.showToastCenter(contextWeakReference,tip,Toast.LENGTH_SHORT,true);
            return;
        }

        downloadCount = 0;
        mDownLoadProgressDlg = new ProgressDialog(mContext);
        //gxw-mProgressDialog.setIcon(R.mipmap.fallalarm);
        mDownLoadProgressDlg.setTitle("提示");
        mDownLoadProgressDlg.setMessage("正在下载新版本...");
        mDownLoadProgressDlg.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        mDownLoadProgressDlg.setMax(100);
        mDownLoadProgressDlg.setCancelable(false);
        mDownLoadProgressDlg.setProgress(0);
        mDownLoadProgressDlg.show();


        GetRequest getRequest = OkHttpUtils.get(url);
        getRequest.tag(url);
        getRequest.execute(new FileCallback(Environment.getExternalStorageDirectory().getAbsolutePath(),
                "aek_ble.apk") {

            @Override
            public void onResponse(boolean isFromCache, File file, Request request, @Nullable Response response) {
                Log.i(TAG, "DOWNLOAD onSuccess");
                if (mDownLoadProgressDlg != null && mDownLoadProgressDlg.isShowing()) {
                    mDownLoadProgressDlg.dismiss();
                    mDownLoadProgressDlg = null;
                }
                downLoadListener.onSuccess();
                install(file, mContext);
            }

            @Override
            public void onError(boolean isFromCache, Call call, @Nullable Response response, @Nullable Exception e) {
                if (mDownLoadProgressDlg != null && mDownLoadProgressDlg.isShowing()) {
                    mDownLoadProgressDlg.setMessage("下载失败,请重新尝试升级");
                    mDownLoadProgressDlg.dismiss();
                }
                downLoadListener.onFailed();
            }


            /**
             * 执行下载过程中的进度回调，UI线程
             *
             * @param currentSize  当前下载的字节数
             * @param totalSize    总共需要下载的字节数
             * @param progress     当前下载的进度
             * @param networkSpeed 当前下载的速度   字节/秒
             */
            public void downloadProgress(long currentSize, long totalSize, float progress, long networkSpeed) {
                Log.i(TAG, "progress=" + progress);

                MyApplication.UPDATE_STATE = 1;  //正在更新
                int pro = (int) (progress * 100);

                if (downloadCount == 0 || pro - 2 > downloadCount) {
                    if (downloadCount != 0) {
                        downloadCount += 2;
                    } else {
                        downloadCount += pro;
                    }
                    downLoadListener.onProgress(pro);
                }

                Log.i(TAG, "progress=" + progress + ",pro=" + pro);

                if (progress > 0.99) {
                    mDownLoadProgressDlg.setMessage("即将自动安装");
                }

                mDownLoadProgressDlg.setProgress(pro);
            }
        });//
        return ;
    }


   /**
     *
     * @param context
     * @param appInfoListener :  监听器的实现在SettingActivity里

     */
    public  void getServerAPPInfo(final Context context, final GetAppInfoListener appInfoListener,final int chekType,int versionCode) {
        String token = User.getTokenHead()+" "+User.getToken();
        OkHttpUtils.get(MyConstant.API_APP_UPDATE)//
                .tag(MyConstant.API_APP_UPDATE)//
                .headers("Authorization",token)
                .params("versionCode",String.valueOf(versionCode))
                .execute(new StringCallback() {
                    @Override
                    public void onResponse(boolean isFromCache, String s, Request request, @Nullable Response response) {
                        int retCode = response.code();
                        if(retCode == 200) {
                            Log.i(TAG,"onSuccess 200 return："+s);
                           try {
                                JSONObject appInfoResult = new JSONObject(s);
                                if(appInfoResult.getString("code").equals("200")) {  //业务正确
                                    AppInfo appInfo= new Gson().fromJson(appInfoResult.getString("data"),AppInfo.class);
                                   //判断是否有新版本
                                    if(mLocalAppVersionCode < appInfo.getVersionCode()) {
                                        appInfo.setHaveNewVersion(1);
                                    }
                                    appInfoListener.onSuccess(appInfo,chekType);
                                }
                                else {
                                    String msg = appInfoResult.getString("message"); //业务错误提示
                                    appInfoListener.onFailed(msg);
                                }
                            }
                            catch (Exception e)
                            {
                                appInfoListener.onFailed("");
                                e.printStackTrace();
                            }
                        }
                        else
                        {
                            appInfoListener.onFailed("请求服务器失败code="+retCode);
                        }
                    }

                    @Override
                    public void onError(boolean isFromCache, Call call, @Nullable Response response, @Nullable Exception e) {
                        String tip = mContext.getResources().getString(R.string.result_server_error);
                        WeakReference<Context> weakReferenceContext = new WeakReference(mContext);
                        MyToast.showToastCenter(weakReferenceContext,tip,Toast.LENGTH_SHORT,true);
                    }
                });


        return ;
    }


    /**
     * 获取 APP版本名称versionName
     */

    public static String getVersionName(Context context){
        //getPackageName()是你当前类的包名，0代表是获取版本信息
        PackageManager packageManager = context.getPackageManager();
        try
        {
            PackageInfo packInfo = packageManager.getPackageInfo(context.getPackageName(),
                    0);
            return packInfo.versionName;
        }catch (Exception e)
        {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取 APP版本ID号： versionCode
     */
    public static int getVersionCode(Context context){

        try
        {
            //getPackageName()是你当前类的包名，0代表是获取版本信息
            PackageManager packageManager = context.getPackageManager();
            PackageInfo packInfo = packageManager.getPackageInfo(context.getPackageName(), 0);
            return packInfo.versionCode;
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        return -1;
    }
}
